﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Models;
using BLL;

namespace Library
{
    public partial class FrmRightManager : Form
    {
        private SysRightManager sysRightManager = new SysRightManager();
        public FrmRightManager()
        {
          
            InitializeComponent();
            this.dgvList.AutoGenerateColumns = false;
            //初始化角色列表
            InitialAdminRoles();
            //展示管理员列表
            GetAllAdmin();
            //展示所有的权限列表
            InitialRightShow();



        }

        #region 初始化

        /// <summary>
        /// 初始化角色列表（其中超级管理员与一班管理员不能进行修改，因此，此处在查询的时候需过滤掉超级管理员与一般管理员）
        /// </summary>
        private void InitialAdminRoles()
        {
            var adminRoleList = sysRightManager.GetAllRoles();
            this.lbRoleList.DataSource = adminRoleList;
            this.lbRoleList.DisplayMember = "RoleName";
            this.lbRoleList.ValueMember = "RoleId";
            //此处数据源如果用同一个adminRoleList，会造成其中一个选项变化时另一个也会跟着变化，隐藏转换成array,进行克隆
            //这个事件在绑定数据源的时候就会触发，解决方法，先将此事件断开，等到数据源绑定完成后在关联
            this.cboRoleList.SelectedIndexChanged -= new System.EventHandler(this.cboRoleList_SelectedIndexChanged);
            this.cboRoleList.DataSource = adminRoleList.ToArray().Clone();
            //这个事件在绑定数据源的时候就会触发，解决方法，先将此事件断开，等到数据源绑定完成后在关联

            this.cboRoleList.DisplayMember = "RoleName";
            this.cboRoleList.ValueMember = "RoleId";
            this.cboRoleList.SelectedValue = -1;
            this.cboRoleList.SelectedIndexChanged += new System.EventHandler(this.cboRoleList_SelectedIndexChanged);
        }

        /// <summary>
        /// 角色权限初始化
        /// </summary>
        public void InitialRightShow()
        {
            var firstMenus = sysRightManager.GetFirstMenus();
            for (int i = 0; i < firstMenus.Count; i++)
            {
                TreeNode treeNode = new TreeNode
                {
                    Name = firstMenus[i].FirstMenuId.ToString(),
                    Text = firstMenus[i].DisplayName
                };
                //根据一级菜单Id获取二级菜单
                var secondMenus = sysRightManager.GetSecondMenus(firstMenus[i].FirstMenuId);
                for (int j = 0; j < secondMenus.Count; j++)
                {
                    treeNode.Nodes.Add(new TreeNode
                    {
                        Name = secondMenus[j].SecondMenuId.ToString(),
                        Text = secondMenus[j].DisplayName,
                        ForeColor = Color.Blue
                    });
                    //根据二级菜单Id获取二级菜单
                    var rightCodes = sysRightManager.GetRightCode(secondMenus[j].SecondMenuId);
                    for (int k = 0; k < rightCodes.Count; k++)
                    {
                        treeNode.Nodes[j].Nodes.Add(new TreeNode
                        {
                            Name = rightCodes[k].RightId.ToString(),
                            Text = rightCodes[k].RightName,
                            ForeColor = Color.Red,
                            Tag = rightCodes[k].RightCode//封装权限编码
                        });
                    }
                }
                this.tvAllRightList.Nodes.Add(treeNode);//加入到treeview节点集合中
            }
            this.tvAllRightList.ExpandAll();//展开所有节点
        }

        #endregion

        #region  窗体拖动、关闭【请自学该内容】

        private Point mouseOff;//鼠标移动位置变量
        private bool leftFlag;//标签是否为左键
        private void FrmMain_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseOff = new Point(-e.X, -e.Y); //得到变量的值
                leftFlag = true;                  //点击左键按下时标注为true;
            }
        }
        private void FrmMain_MouseMove(object sender, MouseEventArgs e)
        {
            if (leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(mouseOff.X, mouseOff.Y);  //设置移动后的位置
                Location = mouseSet;
            }
        }
        private void FrmMain_MouseUp(object sender, MouseEventArgs e)
        {
            if (leftFlag)
            {
                leftFlag = false;//释放鼠标后标注为false;
            }
        }

        #endregion

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //根据角色选择变化动态查询不同的角色列表
        //这个事件在绑定数据源的时候就会触发，解决方法，先将此事件断开，等到数据源绑定完成后在关联
        private void cboRoleList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cboRoleList.SelectedIndex == -1)
            {
                MessageBox.Show("请选择需要查询的角色！","提示信息");
                return;
            }
            var roleId = this.cboRoleList.SelectedValue.ToString();
            //根据角色分类查询角色列表
            this.tvRightList.Nodes.Clear();
            var firstMenus = sysRightManager.GetRoleFirstMenus(roleId);
            for (int i = 0; i < firstMenus.Count; i++)
            {
                TreeNode treeNode = new TreeNode
                {
                    Name = firstMenus[i].FirstMenuId.ToString(),
                    Text = firstMenus[i].DisplayName
                };
                //根据一级菜单Id获取二级菜单
                var secondMenus = sysRightManager.GetRoleSecondMenu(firstMenus[i].FirstMenuId, roleId);
                for (int j = 0; j < secondMenus.Count; j++)
                {
                    treeNode.Nodes.Add(new TreeNode
                    {
                        Name = secondMenus[j].SecondMenuId.ToString(),
                        Text = secondMenus[j].DisplayName,
                        ForeColor = Color.Blue
                    });
                    //根据二级菜单Id获取二级菜单
                    var rightCodes = sysRightManager.GetRoleRightCode(secondMenus[j].SecondMenuId, roleId);
                    for (int k = 0; k < rightCodes.Count; k++)
                    {
                        treeNode.Nodes[j].Nodes.Add(new TreeNode
                        {
                            Name = rightCodes[k].RightId.ToString(),
                            Text = rightCodes[k].RightName,
                            ForeColor = Color.Red,
                            Tag = rightCodes[k].RightCode//封装权限编码
                        });
                    }
                }
                this.tvRightList.Nodes.Add(treeNode);//加入到treeview节点集合中
            }
            this.tvRightList.ExpandAll();//展开所有节点
        }

        #region 角色管理
        /// <summary>
        /// 新增角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddRole_Click(object sender, EventArgs e)
        {
            if (this.txtNewRole.Text.Length == 0 || this.txtRoleDesc.Text.Length == 0)
            {
                MessageBox.Show("角色名称与描述不能为空！");
                return;
            }

            try
            {
                var result = sysRightManager.AddRole(this.txtNewRole.Text, this.txtRoleDesc.Text);
                if (result != 1)
                {
                    MessageBox.Show("角色添加失败！");
                }
                else
                {
                    MessageBox.Show("角色添加成功！");
                    this.txtNewRole.Clear();
                    this.txtRoleDesc.Clear();
                    InitialAdminRoles();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库异常，异常信息："+ex.Message, "错误提示");
            }
        }

        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEidtRoleName_Click(object sender, EventArgs e)
        {
            if (this.lbRoleList.SelectedIndex == -1)
            {
                MessageBox.Show("请选择需要修改的角色!");
                return;
            }

            if (this.txtNewRole.Text.Length == 0 || this.txtRoleDesc.Text.Length == 0)
            {
                MessageBox.Show("角色名称与描述不能为空！");
                return;
            }
            AdminRoles adminRoles = (AdminRoles)this.lbRoleList.SelectedItem;
            try
            {
                var result = sysRightManager.ModifyRole(adminRoles.RoleId, this.txtNewRole.Text, this.txtRoleDesc.Text);
                if (result != 1)
                {
                    MessageBox.Show("角色修改失败！");
                }
                else
                {
                    MessageBox.Show("角色修改成功！");
                    this.txtNewRole.Clear();
                    this.txtRoleDesc.Clear();
                    InitialAdminRoles();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库异常，异常信息：" + ex.Message, "错误提示");
            }
        }

        /// <summary>
        /// 删除决角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelRole_Click(object sender, EventArgs e)
        {
            if (this.lbRoleList.SelectedIndex == -1)
            {
                MessageBox.Show("请选择需要删除的角色!");
                return;
            }
            AdminRoles adminRoles = (AdminRoles)this.lbRoleList.SelectedItem;
            DialogResult dialogResult = MessageBox.Show("确认删除当前选中角色吗？", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dialogResult == DialogResult.Cancel) return;
            try
            {
                var result = sysRightManager.DeleteRole(adminRoles.RoleId);
                if (result != 1)
                {
                    MessageBox.Show("角色删除失败！");
                }
                else
                {
                    MessageBox.Show("角色删除成功！");
                    this.txtNewRole.Clear();
                    this.txtRoleDesc.Clear();
                    InitialAdminRoles();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库异常，异常信息：" + ex.Message,"错误提示");
            }
        }

        /// <summary>
        /// 选择角色变化时清空角色信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbRoleList_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.txtNewRole.Clear();
            this.txtRoleDesc.Clear();
        }

        /// <summary>
        /// 同步展示角色信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbRoleList_DoubleClick(object sender, EventArgs e)
        {
            AdminRoles adminRoles = (AdminRoles)this.lbRoleList.SelectedItem;
            this.txtNewRole.Text = adminRoles.RoleName;
            this.txtRoleDesc.Text = adminRoles.RoleDesc;
        }
        #endregion


        #region 管理员操作
        /// <summary>
        /// 获取管理员列表
        /// </summary>
        public void GetAllAdmin()
        {
            var list = sysRightManager.GetAllAdmin();
            this.dgvList.DataSource = null;
            this.dgvList.DataSource = list;
        }

       
        /// <summary>
        /// 新增管理员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddManager_Click(object sender, EventArgs e)
        {
            if (this.txtAdminName.Text.Trim().Length == 0)
            {
                MessageBox.Show("管理员姓名不能为空！","新增提示");
                this.txtAdminName.Focus();
                return;
            }

            if (this.lbRoleList.SelectedIndex==-1)
            {
                MessageBox.Show("请选择管理员角色！", "新增提示");
                return;
            }

            DialogResult dialogResult = MessageBox.Show("确添加当前角色吗？", "新增提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dialogResult == DialogResult.Cancel) return;
            SysAdmin sysAdmin = new SysAdmin()
            {
                AdminName = this.txtAdminName.Text.Trim(),
                RoleId = Convert.ToInt32(this.lbRoleList.SelectedValue),
                LoginPwd = "123456"
            };
            try
            {
                sysRightManager.AddAdmin(sysAdmin);
                MessageBox.Show("添加成功！", "新增提示");
                GetAllAdmin();//同步更新列表
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库异常，异常信息：" + ex.Message, "错误提示");
            }
        }
        
        /// <summary>
        /// 修改当前选中管理员姓名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEditAdminName_Click(object sender, EventArgs e)
        {
            if (this.dgvList.CurrentRow == null)
            {
                MessageBox.Show("请选择需要修改的管理员！", "提示信息");
                return;
            }

            if (this.txtAdminName.Text.Trim().Length == 0)
            {
                MessageBox.Show("管理员姓名不能为空！", "提示信息");
                this.txtAdminName.Focus();
                return;
            }

            try
            {
                var result = sysRightManager.ModifyAdminName(this.dgvList.CurrentRow.Cells["AdminId"].Value.ToString(), this.txtAdminName.Text.Trim());
                if (result == 1)
                {
                    MessageBox.Show("修改成功！", "提示信息");
                    GetAllAdmin();//同步更新列表
                }
                else
                {
                    MessageBox.Show("修改失败！", "提示信息");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库异常，异常信息：" + ex.Message, "错误提示");
            }

        }

        /// <summary>
        /// 修改当前选中管理员角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEditAdminRoleId_Click(object sender, EventArgs e)
        {
            if (this.dgvList.CurrentRow == null)
            {
                MessageBox.Show("请选择需要修改的管理员！", "提示信息");
                return;
            }

            if (this.lbRoleList.SelectedIndex == -1)
            {
                MessageBox.Show("请选择需要修改的管理员对应的角色！", "提示信息");
                return;
            }
            //这里超级管理员与一般管理员不允许修改，可以根据实际需要选择

            DialogResult dialogResult = MessageBox.Show("确认修改当前管理员角色吗？", "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dialogResult == DialogResult.Cancel) return;
            try
            {
                var result = sysRightManager.ModifyAdminRole(this.dgvList.CurrentRow.Cells["AdminId"].Value.ToString(), this.lbRoleList.SelectedValue.ToString());
                if (result == 1)
                {
                    MessageBox.Show("修改成功！", "提示信息");
                    GetAllAdmin();//同步更新列表
                }
                else
                {
                    MessageBox.Show("修改失败！", "提示信息");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库异常，异常信息：" + ex.Message, "错误提示");
            }
        }

        /// <summary>
        /// 禁用当前选中账号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btndisable_Click(object sender, EventArgs e)
        {
            if (this.dgvList.CurrentRow == null)
            {
                MessageBox.Show("请选择需要禁用的管理员！", "提示信息");
                return;
            }

            if (this.dgvList.CurrentRow.Cells["StatusId"].Value.ToString()=="0")
            {
                MessageBox.Show("该管理已经被禁用，不能再次被禁用！", "提示信息");
                return;
            }

            //这里超级管理员与一般管理员不允许修改，可以根据实际需要选择

            DialogResult dialogResult = MessageBox.Show("确认禁用当前管理员角色吗？", "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dialogResult == DialogResult.Cancel) return;
            try
            {
                var result = sysRightManager.BidAdmin(this.dgvList.CurrentRow.Cells["AdminId"].Value.ToString());
                if (result == 1)
                {
                    MessageBox.Show("禁用成功！", "提示信息");
                    GetAllAdmin();//同步更新列表
                }
                else
                {
                    MessageBox.Show("禁用失败！", "提示信息");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库异常，异常信息：" + ex.Message, "错误提示");
            }
        }

        /// <summary>
        /// 启用当前选中账号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEnable_Click(object sender, EventArgs e)
        {
            if (this.dgvList.CurrentRow == null)
            {
                MessageBox.Show("请选择需要启用的管理员！", "提示信息");
                return;
            }

            if (this.dgvList.CurrentRow.Cells["StatusId"].Value.ToString() == "1")
            {
                MessageBox.Show("该管理处于启用状态，无序再次被启用！", "提示信息");
                return;
            }

            //这里超级管理员与一般管理员不允许修改，可以根据实际需要选择

            DialogResult dialogResult = MessageBox.Show("确认禁用当前管理员角色吗？", "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dialogResult == DialogResult.Cancel) return;
            try
            {
                var result = sysRightManager.AllowAdmin(this.dgvList.CurrentRow.Cells["AdminId"].Value.ToString());
                if (result == 1)
                {
                    MessageBox.Show("启用成功！", "提示信息");
                    GetAllAdmin();//同步更新列表
                }
                else
                {
                    MessageBox.Show("启用失败！", "提示信息");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库异常，异常信息：" + ex.Message, "错误提示");
            }
        }

        /// <summary>
        /// 删除当前选中账号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelAdmin_Click(object sender, EventArgs e)
        {
            if (this.dgvList.CurrentRow == null)
            {
                MessageBox.Show("请选择需要删除的管理员！", "提示信息");
                return;
            }

            //这里超级管理员与一般管理员不允许修改，可以根据实际需要选择

            DialogResult dialogResult = MessageBox.Show("确认删除当前管理员角色吗？", "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dialogResult == DialogResult.Cancel) return;
            try
            {
                var result = sysRightManager.DeleteAdmin(this.dgvList.CurrentRow.Cells["AdminId"].Value.ToString());
                if (result == 1)
                {
                    MessageBox.Show("删除成功！", "提示信息");
                    GetAllAdmin();//同步更新列表：基于集合的时候dgv的数据源，可以直接Refersh();
                }
                else
                {
                    MessageBox.Show("删除失败！", "提示信息");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库异常，异常信息：" + ex.Message, "错误提示");
            }
        }

        //双击展示管理员姓名
        private void dgvList_DoubleClick(object sender, EventArgs e)
        {
            if (this.dgvList.CurrentRow != null)
            {
                this.txtAdminName.Text = this.dgvList.CurrentRow.Cells["AdminName"].Value.ToString();
            }
        }

        //当用户选择的管理员改变时清空管理员姓名
        private void dgvList_SelectionChanged(object sender, EventArgs e)
        {
            this.txtAdminName.Clear();
            if (this.dgvList.CurrentRow.Cells["StatusId"].Value.ToString() == "0")
            {
                this.btndisable.Enabled = false;
                this.btnEnable.Enabled = true;
            }
            else
            {
                this.btndisable.Enabled = true;
                this.btnEnable.Enabled = false;
            }
        }

        #endregion

        #region 权限设定
        private void btnExpand_Click(object sender, EventArgs e)
        {
            this.tvAllRightList.ExpandAll();
        }

        private void btnCollapse_Click(object sender, EventArgs e)
        {
            this.tvAllRightList.CollapseAll();
        }

        /// <summary>
        /// 添加权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            #region 数据校验
            if (this.cboRoleList.SelectedIndex == -1)
            {
                MessageBox.Show("请先选择角色", "提示信息");
                return;
            }
            if (this.tvAllRightList.SelectedNode == null)
            {
                MessageBox.Show("请先选择一个权限节点", "提示信息");
                return;
            }

            if (this.tvAllRightList.SelectedNode.Level !=2)
            {
                MessageBox.Show("请先选择三级红色权限节点", "提示信息");
                return;
            }

            if (this.tvAllRightList.SelectedNode.Text == "【权限管理】")
            {
                MessageBox.Show("该权限不允许设置", "提示信息");
                return;
            }
            var roleId = this.cboRoleList.SelectedValue.ToString();
            var rightId = this.tvAllRightList.SelectedNode.Name;
            if (sysRightManager.QueryRoleRightIsExists(roleId, rightId))
            {
                MessageBox.Show("该角色已经具备该权限！", "提示信息");
                return;
            }
            #endregion
            try
            {
                var result = sysRightManager.AddRoleRight(roleId, rightId);
                if (result > 0)
                {
                    MessageBox.Show("权限设置成功", "提示信息");
                    cboRoleList_SelectedIndexChanged(null, null);
                }
                else
                {
                    MessageBox.Show("权限设置失败", "提示信息");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库异常，异常信息：" + ex.Message, "错误提示");
            }
        }

        /// <summary>
        /// 删除权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDel_Click(object sender, EventArgs e)
        {
            #region 数据校验
            if (this.cboRoleList.SelectedIndex == -1)
            {
                MessageBox.Show("请先选择角色", "提示信息");
                return;
            }
            if (this.tvRightList.SelectedNode == null)
            {
                MessageBox.Show("请先选择一个权限节点", "提示信息");
                return;
            }

            if (this.tvRightList.SelectedNode.Level != 2)
            {
                MessageBox.Show("请先选择三级红色权限节点", "提示信息");
                return;
            }
            DialogResult dialogResult = MessageBox.Show("确认删除当前角色所具备的权限吗？", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dialogResult == DialogResult.Cancel) return;
            var roleId = this.cboRoleList.SelectedValue.ToString();
            var rightId = this.tvRightList.SelectedNode.Name;
            #endregion
            try
            {
                var result = sysRightManager.DeleteRoleRight(roleId, rightId);
                if (result > 0)
                {
                    MessageBox.Show("权限删除成功", "提示信息");
                    cboRoleList_SelectedIndexChanged(null, null);
                }
                else
                {
                    MessageBox.Show("权限删除失败", "提示信息");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库异常，异常信息：" + ex.Message, "错误提示");
            }
        }
        #endregion
    }
}
